<?php

/**
 * CelebrioMail MailSender
 *
 * @copyright  Copyright (c) 2011 Celebrio Software
 * @package    CelebrioMail
 */
namespace ApplicationsModule\MailModule;

use Nette\Mail\SmtpMailer;
use Nette\Mail\Mail;

/**
 * handles working with SMTP and sending e-mails
 * @author Celebrio Software
 */
class MailSender {
    private $mailServer;
    private $mailer;
    private $defaultSubject = "";

    /**
     * handles working with SMTP and sending e-mails
     * @param MailServer $mailServer
     */
    public function __construct($mailServer){
	$this->mailServer = $mailServer;
	$this->defaultSubject = _("Celebrio Mail");
    }

    public function connect() {
	$this->mailer = new SmtpMailer($this->mailServer->getOutServer(),
		$this->mailServer->getOutPort(),
		($this->mailServer->getOutSSL()?"ssl":"tcp"),
		$this->mailServer->getAddress(),
		$this->mailServer->getPassword(),
		"",
		"LOGIN",
		TRUE);
	return TRUE;
    }
    
    /**
     * sends an e-mail
     * @param array $values ("to","subject","contents")
     * @return Mixed returns boolean or an array of undelivered e-mails
     */
    public function sendMail($values) {
	if($this->mailer==NULL){
	    throw new \InvalidStateException("Mailer has not been initialized.");
	    return FALSE;
	}
	$mail = new Mail();
	$mail->setMailer($this->mailer);
	// TODO: improve from (add user name)
	$mail->setFrom($this->mailServer->getAddress());
        $undelivered = array();
	$recipients = explode(",", $values["to"]);
        foreach ($recipients as $email) {
	    $email = trim($email);
	    if($mail != NULL){
		try {
		    // some crazy regex
		    if (!preg_match('/^\s*$/', $email)) {
			// TODO: add support for addCC and addBcc
			$mail->addTo($email);
		    } else {
			$undelivered[] = $email;
		    }
		} catch (\InvalidArgumentException $e) {
		    $undelivered[] = $email;
		}
	    }
        }

        $mail->setSubject($this->defaultSubject);

        $mail->setBody($values["contents"]);

        try {
            $mail->send();
            $undelivered = array_merge(
                $undelivered,
                $this->mailer->getUndeliveredRecipients());

            if (count($undelivered) > 0)
                return $undelivered;
            else
                return TRUE;
        } catch (\InvalidStateException $e) {
            return FALSE;
        }
    }
}